<?php
//问卷调查
if(!defined('IN_T')){
	die('hacking attempt');
}
$act = Common::sfilter($_REQUEST['act']);
if(empty($act)){
	$act = "list";
}

//检查问卷过期
$wenjuan_all = $Db->query("select id,expire_time from ".$Base->table('wenjuan')."");

foreach ($wenjuan_all as $k => $v) {
	if(strtotime($v['expire_time']) < time()){
		$Db->update($Base->table('wenjuan'),array('status'=>2),array('id'=>$v['id']));
	}
}

//检查该用户对该问卷有无操作权限
$wid = intval($_REQUEST['wid']);
if($wid>0){
	$wenjuan_id = $Db->query('select id from '.$Base->table('wenjuan').' where id ='.$wid.' AND pk_user_main ='.$user['pk_user_main'],'Row');

	if(empty($wenjuan_id)){
		die('你没有对该题目的操作权限！');
	}
}
 
$re['status'] = 0;
// var_dump($_lang);
if($act == "add"){

	$wid = intval($_REQUEST['wid']);

	//判断wid是否存在
	$wenjuan = $Db->query("select * from ".$Base->table('wenjuan')." where id=$wid",'Row');
	//非法wid，强制赋值为0
	if(!$wenjuan){
		$wid = 0;
	}

	$wenjuan['jiangxiang'] = $Json->decode($wenjuan['jiangxiang']);
 
	if(empty($_POST)){
		//print_r($wenjuan);
		$tp->assign('wenjuan',$wenjuan);
		// $tp->assign('act','add');

	}else{
		//print_r($_POST['jiangxiang']);exit;

		$wen = array(
		'name'=> Common::sfilter($_REQUEST['name']),
		'reward'=> Common::sfilter($_REQUEST['reward']),
		'score'=> intval($_REQUEST['score']),
		'img_path'=>Common::sfilter($_POST['img_path']),
		'expire_time'=> Common::sfilter($_REQUEST['expire_time']),
		'create_time'=>date('Y-m-d H:i:s',time()),
		'pro'=>intval($_REQUEST['pro']),
		);

		//组装奖项设置
		$jiang = $_POST['jiangxiang'];
		$jiang_tmp = array();
		foreach($jiang['name'] as $k=>$v){
			$name = Common::sfilter($v);
			if(empty($name)){
				$re['msg'] = '奖品名称不能为空';
				echo $Json->encode($re);
				exit;
			}
			$jiang_tmp[$k]['name'] = $name;
		}
		foreach($jiang['num'] as $k=>$v){
			$num = intval($v);
			if($num<1){
				$re['msg'] = '奖品数量必须大于0';
				echo $Json->encode($re);
				exit;
			}
			$jiang_tmp[$k]['num'] = $num;	
		}
		foreach($jiang['remain'] as $k=>$v){
			$remain = intval($v);
			$jiang_tmp[$k]['remain'] = $remain;
		}
		//print_r($jiang_tmp);exit;

		if(empty($wen['name'])){
			$re['msg'] = '问卷的名称不能为空！';
		}else if(empty($wen['reward'])){
			$re['msg'] = '活动描述不能为空！';
		}else if($wen['score']<1){
			$re['msg'] = '问卷的中奖分值不能小于1';
		}else if(empty($wen['expire_time'])){
			$re['msg'] = '问卷的过期时间不能为空！';
		}
		else if(empty($jiang_tmp)){
			$re['msg'] = '奖项设置不能为空';
		}else if($wen['pro']<0 && $wen['pro']>100){
			$re['msg'] = '中奖概率须介于0-100';
		}
		else{
			$wen['jiangxiang'] = $Json->encode_unescaped_unicode($jiang_tmp);
			//print_r($wen);exit;
			//编辑
			if($wid>0){
				//编页面提交问卷的详细信息
				$wen['id'] = $wid;
				$wen['pk_user_main'] = $user['pk_user_main'];
				if(strtotime($wen['expire_time'])>time()){
					$wen['status'] = 1;
				}
			}
			//添加
			else{
				$wen['pk_user_main'] = $user['pk_user_main'];
			}



			//将问卷信息写入数据库
			$id = $Db->replace($Base->table('wenjuan'),$wen);

			if($id > 0){
				ob_clean();
				$re = array('status'=>1,'msg'=>'提交成功','href'=>'/member/wenjuan');

			}else{

				$re['msg'] ='服务器繁忙，稍后重试！';

			}

		}

		echo $Json->encode($re);
	    exit;
	}
	
}
else if($act == 'list_wen'){

	$page = intval($_REQUEST['page'])<1 ? 1 : intval($_REQUEST['page']);

	$pageSize = 10;

	$name = Common::sfilter($_REQUEST['name']);

	$status = intval($_REQUEST['status']);
	
	$res = list_wenjuan( $page,$pageSize,$user['pk_user_main'],$name,$status);

	echo $Json->encode($res);
	exit;

}else if($act == "delete"){

	$wid = intval($_REQUEST['wid']);


	$Db->delete($Base->table('wenJuan'),array('id'=>$wid,'pk_user_main'=>$user['pk_user_main']));

	//同时删除问卷详情表
	$Db->delete($Base->table('subject'),array('wid'=>$wid));

	//同时删除问卷反馈表
	$Db->delete($Base->table('wenJuan_fankui'),array('wid'=>$wid));

	$re = array('status'=>1,'msg'=>'删除成功');

	echo $Json->encode($re);
	exit;
}else if($act == "subject"){
	$wid = intval($_REQUEST['wid']);
	$wenjuan = $Db->query("select * from ".$Base->table('wenjuan')." where id=$wid",'Row');
	$subjects = $Db->query("select * from ".$Base->table('subject')." where wid=$wid ORDER BY sort");
	//显示题目列表


	if(empty($_POST)){
		//todo
		foreach($subjects as $k=>$v){
		
			$subjects[$k]['answer']=$Json->decode($v['values']);
			// var_dump($subject[$k]['answer']);
			
		}
		// var_dump($subject);
		$tp->assign('wenjuan',$wenjuan);
		$tp->assign('subject',$subjects);
	}
	//添加、编辑题目
	else{
		$sid = intval($_POST['sid']);	//题目id

		$subject = $Db->query("select * from ".$Base->table('subject')." where id=$sid",'Row');
		//提取某个题目的详细
		if($_POST['detail']==1){

			$subject['values'] = $Json->decode($subject['values']);
			// $subject['values']['num']=count($Json->decode($subject['values']));
			echo $Json->encode($subject);
			exit;
		}
		//添加、编辑题目
		else{
			// print_r($_POST);
			//组装题目数据
			foreach($_POST['asnwer'] as $k=>$v){
				$answer[$k]['answer'] = $_POST['asnwer'][$k];
				if(in_array($k,$_POST['check'])){
					$answer[$k]['selected'] = 1;
				}
				else{
					$answer[$k]['selected'] = 0;
				}
			}


			$answer = $Json->encode_unescaped_unicode($answer);
	
			// print_r($answer_all);
			$data = array(
				'name'=>Common::sfilter($_REQUEST['name']),
				'wid'=>Common::sfilter($_REQUEST['wid']),
				'values'=> $answer
			);
			$re['status'] = 0;
			// var_dump($_POST['asnwer']);

			if(empty($data['name'])){
				$re['msg'] = "问题描述不能为空！请填写";
			}else if(empty($_POST['asnwer'])){
				$re['msg'] = "还没有填写答案！请填写";
			}
			// else if(empty($_POST['check'])){
			// 	$re['msg'] = "还没有选择正确答案！请选择";
			// }
			else{
				//编辑
				if($subject){
					$datas['id'] = $sid;
					$Db->update($Base->table('subject'),$data,$datas);
					$re = array('msg'=>'修改成功','status'=>'1','href'=>'/member/wenjuan?act=subject&wid='.$wid);
				}
				//添加
				else{
					$id = $Db->insert($Base->table('subject'),$data);
					$sort['sort'] = $id;
					$oid['id'] = $id;
					$Db->update($Base->table('subject'),$sort,$oid);
					$re = array('msg'=>'添加成功','status'=>'1','href'=>'/member/wenjuan?act=subject&wid='.$wid);
				}
			}
			
			echo $Json->encode($re);
			exit;
		}
		
	}	

}else if($act == "answer_delete"){
	$sid = intval($_REQUEST['sid']);


	$Db->delete($Base->table('subject'),array('id'=>$sid));


	$re = array('status'=>1,'msg'=>'删除成功');

	echo $Json->encode($re);
	exit;
}else if($act == "answer_up"){

	$re['status'] = 0;
	$sid = intval($_REQUEST['sid']);
	$wid = intval($_REQUEST['wid']);

	//读出该问卷的所有问题
	$q_all = $Db->query("select id,sort from ".$Base->table('subject')." where wid = $wid ORDER BY sort");

	// var_dump($q_all);

	foreach($q_all as $k => $v){
		if($v['id'] == $sid){
			$sortup = $v['sort'];
			$idup = $sid;
			$num = $k;
		}
	}
	$sortdown = $q_all[$num-1]['sort'];
	$iddown = $q_all[$num-1]['id'];
	// var_dump($num);
	// var_dump($sortup.','.$idup);
	// var_dump($sortdown.','.$iddown);die;
	if($num > 0){

		$Db->update($Base->table('subject'),array('sort'=>$sortdown),array('id'=>$idup));
		$Db->update($Base->table('subject'),array('sort'=>$sortup),array('id'=>$iddown));
		$re = array('status'=>1,'msg'=>'排序修改成功！');
	}else{
		$re['msg'] = ' 该问题已经是第一个了！';
	}

	echo $Json->encode($re);
	exit;
}else if($act == "answer_list"){

		if(Common::sfilter($_REQUEST['lin'])){
			$done['done'] = 1;

			$oid['id'] = Common::sfilter($_REQUEST['oid']);

			if(Common::sfilter($_REQUEST['del'])){
				$Db->delete($Base->table('wenjuan_fankui'),$oid);
			}else{
				$Db->update($Base->table('wenjuan_fankui'),$done,$oid);
			}
			
			$res=array('status'=>1,'msg'=>'操作成功！');

			echo $Json->encode($res);

			exit;
		}
		$page = intval($_REQUEST['page'])<1 ? 1 : intval($_REQUEST['page']);

		$pageSize = 20;

		$phone = Common::sfilter($_REQUEST['phone']);

		$done = Common::sfilter($_REQUEST['done']);

		if($done>1){
			unset($done);
		}
		
		$res = list_wenjuan_fankui($page,$pageSize,$user['pk_user_main'],$done,$phone);

		echo $Json->encode($res);

		exit;
	
	
}else if($act == 'slide'){
	$dir_path = 'data/wenjuan';
	Common::make_dir($dir_path);
	$file_path = $dir_path.'/'.Common::gmtime().'.png';
	$data['error'] = 1;
	if(move_uploaded_file($_FILES['imgFile']['tmp_name'],$file_path)){
		$data = array('error'=>0,'url'=>'/'.$file_path);
	}
	else{
		$data['message'] = '上传失败！';
	}
	echo $Json->encode($data);
	exit;
}

$tp->assign('act',$act);

function list_wenjuan($page,$pageSize,$user,$name,$status){

	$sql = 'FROM'.$GLOBALS['Base']->table('wenjuan');
	
	$sql.=' WHERE pk_user_main='.$user;

	if($status > 0){
		$sql .=" AND status = ".$status;
	}

	if(!empty($name)){
		$sql .=" AND name LIKE '%$name%' ";
	}

	$list = $GLOBALS['Db']->query('SELECT * '.$sql.' '.
		    'ORDER BY create_time DESC , id DESC LIMIT '.($page-1)*$pageSize.','.$pageSize);

	foreach($list as $k=>$v){
		$jiangxiang = $GLOBALS['Json']->decode($v['jiangxiang']);
		$jiang_tmp = array();
		foreach($jiangxiang as $v2){
			//print_r($v2);
			$jiang_tmp[] = $v2['name'].'('.$v2['num'].'/'.$v2['remain'].')';
		}
		$list[$k]['jiangxiang'] = "奖项设置：".implode('；',$jiang_tmp);
	}
	//print_r($list);exit;
	$itemCount = $GLOBALS['Db']->query(" SELECT COUNT(*) AS num ".$sql,"One");
	$pageCount = ceil($itemCount/$pageSize);

	$res = array(
			'pageCount'=>$pageCount,
			'currentPage'=>$page,
			'pageSize'=>$pageSize,
			'list'=>$list,
	);

	return $res;
}

function list_wenjuan_fankui($page,$pageSize,$user,$done,$phone){


	$sql = "".$GLOBALS['Base']->table('wenjuan_fankui')." as f ".
			" left join ".$GLOBALS['Base']->table('wenjuan')." as w on f.wid=w.id ".
			"where w.pk_user_main =".$user;


	if(isset($done)){
		//区分有没领奖的前提是中奖
		$sql.=" AND f.done = ".$done." AND f.reward != ''";
	}

	if(!empty($phone)){
		$sql.=" AND f.user LIKE '%$phone%' ";
	}
	// var_dump($done);
	// var_dump($sql);die;
	$itemCount = $GLOBALS['Db']->query('select count(*) from '.$sql,'One');
	// var_dump($itemCount);
	$pageCount = ceil($itemCount/$pageSize);

	$list = $GLOBALS['Db']->query('select f.*,w.name as wname from '.$sql.' ORDER BY id DESC LIMIT '.($page-1)*$pageSize.','.$pageSize);
	// var_dump('select f.*,w.name as wname from '.$sql.' ORDER BY id DESC LIMIT '.($page-1)*$pageSize.','.$pageSize);
	$res = array(

		'pageCount'=>$pageCount,
		'currentPage'=>$page,
		'pageSize'=>$pageSize,
		'list'=>$list,

		);

	return $res;

}




?>